define(['template/page/indexTpl','qrcode','wx','wx.ajax','wx.tpl','wx.pop','wx.upload','wx.validator','vendor/jquery.ztree.all-3.5','vendor/ueditor/ueditor.config','vendor/ueditor/ueditor.all'],function(tpl,qrcode,wx){
    var page = {};
    var isWrite;
    var currentOpenId;
    var ue;
    function init(id,w){
        isWrite = w;
        var t = new Date().getTime();
        $.when(
            $.ajax('/res/css/page.css?_='+t),
            $.ajax('/res/css/zTreeStyle.css')
        ).done(function(pageCss,ztreeCss){
            $('<style type="text/css">').append(pageCss[0],ztreeCss[0]).appendTo('head');
            wx.sendData('/resource/all','type=1',initTree);
        });
	}
    function destroy(){
        if(ue){
            ue.destroy();
            ue = null;
        }
        return true;
    }
    function max(width,height){
        ue && ue.setHeight(height-92);
        $('#Js-container,#Js-page-list,#Js-page-body').height(height-10);
    }
    function resize(width,height){
        ue && ue.setHeight(height-130);
        $('#Js-container,#Js-page-list,#Js-page-body').height(height-10);
    }
    function restore(width,height){
        height-=40;
        ue && ue.setHeight(height-130);
        $('#Js-container,#Js-page-list,#Js-page-body').height(height);
    }

    function initTree(data){
        for (var i = data.result.length - 1; i >= 0; i--) {
            data.result[i].isParent = data.result[i].isParent == '1' ?true:false;
        }
        $('#window-frame-page').html(tpl.container);
        $('#window-bar-page').html('<marquee>使用说明：按住ctrl拖动文件为复制。按住ctrl点击文件为打开新页面查看</marquee>');

        var setting = {
            view: {
                showLine: true,
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable:true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: ""
                },
                keep:{
                    leaf:true,
                    parent:true
                }
            },
            edit: {
                enable: true,
                editNameSelectAll: true,
                showRemoveBtn: showRemoveBtn,
                drag: {
                    isCopy:true,
                    autoExpandTrigger: true
                }
            },
            callback: {
                onClick:Onclick,
                onDblClick:OnDdClick,
                onMouseDown: OnMouseDown,
                onRightClick: OnRightClick,
                beforeRemove: beforeRemove,
                beforeDrag: beforeDrag,
                beforeDrop: beforeDrop,
                onRemove: OnRemove,
                onRename: OnRename
            }
        };
        $.fn.zTree.init($('#Js-page-list'), setting,data.result);

        baidu.editor.commands['save'] = {
            execCommand : function() {
                setStyle(this.getContent(),this.document);
                var ueContent = this.getContent().replace(/"/g,'\'').replace(/[\r\n]/g, '<br>').replace(/&nbsp;/g, ' ');
                var _this = this;
                var body = ueContent;
                var content = {
                    body:body,
                    weixin:UE.weixin||{}
                };
                var pageinfo = {
                    background :$('<div>'+this.getContent()+'</div>').find('p[data-background]').data('background')|| null
                };
                wx.sendData('/resource/save-content',{data:{'moduleName':'page','id':currentOpenId,'content':JSON.stringify(content),'fronturl':frontWebUrl+'/page/'+currentOpenId+'.html'}},function(data){
                    wx.sendData('/resource/save-pageinfo',{data:{'id':currentOpenId,'info':JSON.stringify(pageinfo)}});
                    if(data.status == 0){
                        _this.trigger('showmessage',{
                            content : '保存成功',
                            timeout : 2000
                        });
                    }
                });
             return true;
            },
            queryCommandState : function(){}
        };

        $('#Js-container,#Js-page-list,#Js-page-body').height($('#window-frame-page').height());

        require(['vendor/ueditor/third-party/zeroclipboard/ZeroClipboard'],function(){
            ZeroClipboard.config({swfPath: "/res/js/vendor/ueditor/third-party/zeroclipboard/ZeroClipboard.swf" });
        });
    }

    function addHoverDom(treeId, treeNode){
        if(treeNode.isParent === false && $("#diyBtn_space_" +treeNode.id).length === 0){
            var qr = "<span id='diyBtn_space_" +treeNode.id+ "' class='button qrcode'  title='二维码' onfocus='this.blur();'></span>";
            $('#'+treeNode.tId+'_edit').before(qr);
            $('#diyBtn_space_' +treeNode.id).off('click').on('click',function(event) {
                $("#qrcode_"+treeNode.id).empty();
                wx.pop('<div id="qrcode_'+treeNode.id+'" class="ztree-qrcode"></div>',{layerClick:true});
                new QRCode($('#qrcode_'+treeNode.id)[0], {
                    width : 175,
                    height : 175
                }).makeCode(frontWebUrl+'/page/'+treeNode.id+'.html?t='+(new Date().getTime()));

            });
        }
    }

    function removeHoverDom(treeId, treeNode) {
        $("#diyBtn_space_" +treeNode.id).remove();
    }

    function showRemoveBtn(treeId, treeNode) {
        if(treeNode.children)
            return false;
        else
            return true;
    }

    function Onclick(event, treeId, treeNode,clickFlag){
        if(treeNode.isParent === false && clickFlag === 0){
            window.open(frontWebUrl+'/page/'+treeNode.id+'.html?t='+(new Date().getTime()));
        }
    }

    function OnMouseDown(event, treeId, treeNode) {
        if(treeNode){
            var info = '上次修改人：'+treeNode.modify_by+'&nbsp;&nbsp;&nbsp;&nbsp;     修改时间：'+treeNode.modify_time+'&nbsp;&nbsp;&nbsp;&nbsp; | &nbsp;&nbsp;&nbsp;&nbsp;'+'创建人：'+treeNode.create_by+'&nbsp;&nbsp;&nbsp;&nbsp;     创建时间：'+treeNode.create_time;
            $('#window-bar-page').html(info);
        } else {
            $.fn.zTree.getZTreeObj("Js-page-list").cancelSelectedNode();
        }
    }

    function OnDdClick(event, treeId, treeNode){
        if(treeNode && !treeNode.isParent){
            currentOpenId = treeNode.id;

            if(ue){
                ue.destroy();
                ue = null;
            }

            ue = UE.getEditor('Js-page-code',{
                initialFrameWidth:null,
                autoFloatEnabled:false,
                scaleEnabled:true,
                initialFrameHeight:$('#Js-page-body').height()-130
            });
            ue.setOpt('insertcode',{
                'css':'Css',
                'js':'Javascript'
            });
            ue.setOpt('imageScaleEnabled',false);

            ue.addshortcutkey(
                "save" , "ctrl+83"
            );

            ue.ready(getContent);
        }
    }

    function getContent(){
        wx.sendData('/resource/content','id='+currentOpenId,function(data){
            if(data.result.content && data.result.content.length>0){
                var d = JSON.parse(data.result.content);
                ue.setContent(d.body);
                UE.weixin = d.weixin;
                setStyle(d.body,ue.document)
            } else {
                ue.setContent('');
            }
            ue.undoManger && ue.undoManger.save(true);//解决再次打开editor时背景色不显示问题
        });
    }

    function setStyle(body,doc){
        var css ='';
        body = body.replace(/\&nbsp;|<br>/g, '');
        $('<div>'+body+'</div>').find('pre[css]').each(function(index,content){
           css+=$(content).html();
        });
        $(doc).find('#ownerStyle').remove();
        $(doc).find('head').append('<style id="ownerStyle">'+css+'</style>');
    }

    function OnRightClick(event, treeId, treeNode){
        $('#Js-page-contextmenu').remove();
        var menu = false;
            menu = treeNode && treeNode.isParent;
        
        var zTree = $.fn.zTree.getZTreeObj("Js-page-list");
        zTree.selectNode(treeNode);
        if(menu === false){
            $('body').append(wx.tpl(tpl.copy,event));
            var client = new ZeroClipboard($('#Js-page-copy'));
            $("body").one("click", function(){
                $('#Js-page-contextmenu').remove();
            });
            client.on( "copy", function (event) {
                event.clipboardData.setData("text/plain",frontWebUrl+'/page/'+treeNode.id+'.html');
                $('#Js-page-contextmenu').remove();
                $('#window-bar-page').html('地址拷贝成功！');
                setTimeout(function(){$('#window-bar-page').html('');},3000);
            });

        } else{
            $('body').append(wx.tpl(tpl.contextmenu,event));
            $('#Js-page-addFile').one('click',function(event) {
                createNode(event,0,treeId, treeNode);
                $("body").trigger('click');
            });
            $('#Js-page-addCate').one('click',function(event) {
                createNode(event,1,treeId, treeNode);
                $("body").trigger('click');
            });
            $("body").one("click", function(){
                $('#Js-page-contextmenu').remove();
            });
        }
    }

    function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
        if(isCopy){
            wx.sendData('resource/copy','sourceId='+treeNodes[0].id+'&pId='+targetNode.id,function(data){
                treeNodes.id = data.result.id;
            });
        } else {
            wx.sendData('resource/move','id='+treeNodes[0].id+'&targetId='+targetNode.id);
        }
        return true;
    }
    function beforeDrag(treeId, treeNodes) {
        if(treeNodes[0].isParent)
            return false;
        else
            return true;
    }

    function OnRename(event, treeId, treeNode, isCancel) {
        wx.sendData('/resource/rename','id='+treeNode.id+'&name='+treeNode.name);
    }

    function OnRemove(event, treeId, treeNode, isCancel) {
        wx.sendData('/resource/remove','id='+treeNode.id);
    }

    function beforeRemove(treeId, treeNode) {
        return confirm("确认删除 " + treeNode.name + " 吗？");
    }

    function createNode(event,isParent,treeId,treeNode){
        var pId = treeNode?treeNode.id:0;
        wx.sendData('/resource/create','type=1&isParent='+isParent+'&pId='+pId,function(data){
            add(event,data.result.id,isParent);
        });
    }

    function add(event,id,type){
        var zTree = $.fn.zTree.getZTreeObj("Js-page-list"),
        isParent = type,
        nodes = zTree.getSelectedNodes(),
        treeNode = nodes[0];
        if (treeNode) {
            treeNode = zTree.addNodes(treeNode, {id:id, pId:treeNode.id, isParent:isParent, name:"新节点" + id});
        } else {
            treeNode = zTree.addNodes(null, {id:id, pId:0, isParent:isParent, name:"新节点" + id});
        }
        if (treeNode) {
            zTree.editName(treeNode[0]);
        } else {
            alert("叶子节点被锁定，无法增加子节点");
        }
    }

    function onBodyMouseDown(){
        setTimeout(function(){
            $('#Js-page-contextmenu').remove();
        },100);
    }

    page.init = init;
    page.max = max;
    page.restore = restore;
    page.resize = resize;
    page.destroy = destroy;
    return page;
});